from django.conf import settings
from django.shortcuts import render

# Create your views here.
from fdfs_client.client import Fdfs_client
from rest_framework.generics import RetrieveAPIView, GenericAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, ViewSet

from houses import serializers
from houses.models import House, Facility, HouseImage, Area
from houses.my_paginate import MyPageNumberPagination
from houses.serializers import HouseSerializer
from orders.models import Order
from users.models import User
import datetime


class AreasView(GenericAPIView):
    serializer_class = serializers.AreasSerializer

    def get_queryset(self):
        queryset = Area.objects.all()
        data = []
        for city in queryset:
            city_data = {
                'aid': city.id,
                'aname': city.name
            }
            data.append(city_data)
        return data

    def get(self, request):
        data = self.get_queryset()
        return Response({"errmsg": "获取成功", "errno": "0", "data": data})


class HouseDetailView(RetrieveAPIView):
    queryset = House.objects.all()
    serializer_class = HouseSerializer

    def retrieve(self, request, *args, **kwargs):
        house = self.get_object()
        orders = Order.objects.filter(house=house)
        user = request.user

        comments = []
        for order in orders:
            data = {
                'comment': order.comment,
                'ctime': order.update_time,
                'user_name': User.objects.get(id=order.user_id).username
            }
            comments.append(data)

        facilities = house.facility.all()
        house_facilities = []
        for facility in facilities:
            house_facilities.append(facility.id)

        images = HouseImage.objects.filter(house=house)
        house_images = []
        for image in images:
            url = "http://image.ihome.site:8888/" + image.url
            house_images.append(url)

        house = {
            "acreage": house.acreage,
            "address": house.address,
            "beds": house.beds,
            "capacity": house.capacity,
            "comments": comments,
            "deposit": house.deposit,
            "facilities": house_facilities,
            "hid": house.id,
            "img_urls": house_images,
            "max_days": house.max_days,
            "min_days": house.min_days,
            "price": house.price,
            "room_count": house.room_count,
            "title": house.title,
            "unit": house.unit,
            "user_avatar": house.user.avatar.url,
            "user_id": house.user.id,
            "user_name": house.user.username
        }
        user_id = user.id if user else -1
        res = {
            'data': {
                'house': house,
                'user_id': user_id
            },
            'errno': '0',
            "errmsg": "OK"
        }
        return Response(res)


class HouseSearchView(ModelViewSet):
    serializer_class = HouseSerializer
    pagination_class = MyPageNumberPagination
    queryset = House.objects.all()

    def create(self, request, *args, **kwargs):
        data = request.data
        user = request.user
        acreage = data.get('acreage')
        address = data.get('address')
        area_id = data.get('area_id')
        beds = data.get('beds')
        capacity = data.get('capacity')
        deposit = data.get('deposit')
        max_days = data.get('max_days')
        min_days = data.get('min_days')
        price = data.get('price')
        room_count = data.get('room_count')
        title = data.get('title')
        unit = data.get('unit')
        # 数据进行校验
        # 1,对数据完整性校验
        if not all([acreage, address, area_id, beds, capacity, deposit, max_days, min_days, price, room_count, title,
                    unit]):
            return Response({"errmsg": "参数不全，请重新输入", "errno": "9999"})
        try:
            new_price = int(float(price) * 100)
            new_deposit = int(float(deposit) * 100)
        except Exception as e:
            return Response({"errmsg": "价格输入有误", "errno": "9999"})
        # 4,对地区进行校验
        try:
            area = Area.objects.get(id=area_id)
        except Exception as e:
            return Response({"errmsg": "地区输入有误", "errno": "9999"})
        try:
            user_data = User.objects.get(id=user.id)
        except Exception as e:
            return Response({"errmsg": "用户不存在", "errno": "9999"})
        house = {
            'user': user_data,
            'area': area,
            'title': title,
            'price': price,
            'address': address,
            'room_count': room_count,
            'acreage': acreage,
            'unit': unit,
            'capacity': capacity,
            'beds': beds,
            'deposit': deposit,
            'min_days': min_days,
            'max_days': max_days
        }
        new_house = House.objects.create(**house)
        facility = data.get('facility')
        if facility:
            try:
                facilities = Facility.objects.filter(id__in=facility)
            except Exception as e:
                return Response({"errmsg": "选项输入有误", "errno": "9999"})
            if facilities:
                new_house.facility.add(*facility)
                new_house.save()
        return Response({
            "errno": "0",
            "errmsg": "发布成功",
            "data": {"house_id": new_house.id}
        })

    def get_queryset(self):
        aid = self.request.query_params.get('aid')
        sd = self.request.query_params.get('sd')
        ed = self.request.query_params.get('ed')
        sk = self.request.query_params.get('sk')
        houses_dict = []
        if aid:
            houses = House.objects.filter(area_id=aid)
        else:
            houses = House.objects.all()
        orders = Order.objects.filter(house__in=houses)
        if sd:
            sd_datetime = datetime.datetime.strptime(sd, "%Y-%m-%d")
            if ed:
                ed_datetime = datetime.datetime.strptime(ed, "%Y-%m-%d")
                if sd > ed:
                    return Response({'errno':9999,'errmsg':'开始时间大于结束时间'})
                for order in orders:
                    end_time = datetime.datetime.strptime(order.end_date.strftime("%Y-%m-%d"), "%Y-%m-%d")
                    begin_time = datetime.datetime.strptime(order.begin_date.strftime("%Y-%m-%d"), "%Y-%m-%d")
                    if not sd_datetime > end_time or ed_datetime < begin_time:
                        if order.status not in [5, 6]:
                            houses = houses.exclude(id=order.house_id)
            else:
                for order in orders:
                    end_time = datetime.datetime.strptime(order.end_date.strftime("%Y-%m-%d"), "%Y-%m-%d")
                    if sd_datetime < end_time :
                        if order.status not in [5, 6]:
                            houses = houses.exclude(id=order.house_id)
        if sk == 'price-inc':
            houses_dict = houses.order_by('price')
        if sk == 'price-des':
            houses_dict = houses.order_by('-price')
        if sk == 'booking':
            houses_dict = houses.order_by('order_count')
        if sk == 'new':
            houses_dict = houses.order_by('-create_time')
        return houses_dict
    def list(self, request, *args, **kwargs):
        # aid = request.query_params.get('aid')
        # sd = request.query_params.get('sd')
        # ed = request.query_params.get('ed')
        # sk = request.query_params.get('sk')
        #
        # if sd:
        #     sd_datetime = datetime.datetime.strptime(sd, "%Y-%m-%d")
        # if ed:
        #     ed_datetime = datetime.datetime.strptime(ed, "%Y-%m-%d")
        # houses_dict = []
        # if aid:
        #     houses = House.objects.filter(area_id=aid)
        # else:
        #     houses = self.get_queryset()
        # orders = Order.objects.filter(house__in=houses)
        # for order in orders:
        #     end_time = datetime.datetime.strptime(order.end_date.strftime("%Y-%m-%d"), "%Y-%m-%d")
        #     begin_time = datetime.datetime.strptime(order.begin_date.strftime("%Y-%m-%d"), "%Y-%m-%d")
        #     if not sd_datetime > end_time or ed_datetime < begin_time:
        #         if order.status not in [5, 6]:
        #             houses = houses.exclude(id=order.house_id)
        # if sk == 'price-inc':
        #     houses_dict = houses.order_by('price')
        # if sk == 'price-des':
        #     houses_dict = houses.order_by('-price')
        # if sk == 'booking':
        #     houses_dict = houses.order_by('order_count')
        # if sk == 'new':
        #     houses_dict = houses.order_by('-create_time')
        houses_dict = self.get_queryset()
        page = self.paginate_queryset(houses_dict)

        serializer = self.get_serializer(page, many=True)

        return self.get_paginated_response(serializer.data)


class HouseImageView(GenericAPIView):
    serializer_class = serializers.HouseSerializer
    queryset = House.objects.all()

    def post(self, request, pk):
        house = self.get_object()
        image = request.FILES.get('house_image')
        if not all([house, image]):
            return Response({"errno": "9999", "errmsg": "参数不全"})
        client = Fdfs_client('/home/python/Desktop/ihome_project/ihome_project/ihome/utils/fdfs/client.conf')
        result = client.upload_by_buffer(image.read())
        if result['Status'] != 'Upload successed.':
            return Response({"errno": "9999", "errmsg": "图片上传失败"})
        image_url = result["Remote file_id"]  # 取出图片url
        house.index_image_url = image_url
        house.save()
        return Response({
            "data": {
                "url": settings.BASE_URL + image_url
            },
            "errno": "0",
            "errmsg": "图片上传成功"
        })

class HousesListView(APIView):
    def get(self,request):
        user = request.user
        houses = House.objects.filter(user__mobile=user.mobile)
        user_data = User.objects.get(mobile=user.mobile)
        houses_list=[]
        for house in houses:
            house_dict={
                "address": house.address,
                "area_name": house.area.name,
                "ctime": house.create_time,
                "house_id": house.id,
                "img_url": settings.BASE_URL + house.index_image_url,
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": user_data.avatar.url
                }
            houses_list.append(house_dict)
        context={'houses':houses_list}
        return Response({"errmsg": "ok", "errno": "0", "data": context})


class HouseIndexView(GenericAPIView):
    queryset = House.objects.all().order_by('order_count')[0:5]
    serializer_class = HouseSerializer
    def get(self,request):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        home_list = []
        for indexhouse in serializer.data:
            data ={}
            data['img_url'] = settings.BASE_URL + indexhouse['index_image_url']
            data['house_id'] = indexhouse['id']
            data['title'] = indexhouse['title']
            home_list.append(data)
        res = {"data":home_list, "errmsg": "OK", "errno": "0"}
        return Response(res)